package com.hd.contentmonitor.service;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import com.hd.contentmonitor.jdbc.JDBCConnection;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

/*
 *<p>This class is responsible for parsing the content and the html tag element's attributes values.</p> 
 */

public class WebContentMonitor{	 
	 
	 public static void main(String args[]){
		 System.out.println("going to generate");
		 WebContentMonitor webcontentMonitor = new WebContentMonitor();
	 }
	
	
	public  WebContentMonitor(){		
		try {
			
			FileOutputStream out = new FileOutputStream("D:\\webcontentmonitor.txt");
			PrintStream ps = null;
			 if (out != null){
	             //log file
	             ps = new PrintStream( out );
	             System.setOut(ps); //redirects stderr to the log file as well
	
	         }
		}catch(IOException e){
			e.printStackTrace();
		}
		
		List<String> listUrl = getURLs();
		WebDriver driver = new FirefoxDriver();	
		
		try{
			
			for(String url:listUrl){	 
				getBodyHTML(url,driver);
			}
			
			File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
			// Now you can do whatever you need to do with it, for example copy somewhere
			FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
			
			driver.quit();
	         
	    
		}catch(Exception io){
			io.printStackTrace();
		}
	}
	
	
	private static List<String> getURLs(){
		File htmlTagElementsListFile;
		FileInputStream finStream;
		DataInputStream dinStream;
		BufferedReader buffReader;
		String htmlTagElement = "";
		List<String> urlList =new ArrayList<String>();
		String currentline =null;
		List<List<String>> arrList = new ArrayList<List<String>>();
		try {
			htmlTagElementsListFile = new File("D:\\listUrl.cfg");
			finStream = new FileInputStream(htmlTagElementsListFile);
			dinStream = new DataInputStream(finStream);
			buffReader = new BufferedReader(new InputStreamReader(dinStream));
			currentline=buffReader.readLine();
			while(currentline!=null){
				if(currentline != null)
					urlList.add(currentline.trim());
				currentline=buffReader.readLine();
			}
			dinStream.close();
		} catch (FileNotFoundException fnfEx) {
			fnfEx.printStackTrace();
			//log.error(fnfEx.getMessage());
		}
		catch (Exception ex) {
			ex.printStackTrace();
			//log.error(ex.getMessage());
		}
		System.out.println("list of url.."+urlList.size());
		return urlList;
	}
	

	 public static void getBodyHTML(String url,WebDriver driver){
		 try{
			 //String htmlString = "";
			 String tempHtmlFileName="D:\\temp1.html";
			 String tempHtml1FileName="D:\\tempold1.html";
			 driver.get(url);    
	        // String source=driver.getPageSource();
	         WebElement elem=driver.findElements(By.tagName("body")).get(0);
	         String source = elem.getAttribute("innerHTML");
	         
	         FileOutputStream fileout = new FileOutputStream(new File(tempHtmlFileName));
	         fileout.write(source.trim().getBytes());
	         fileout.close();

	         
	         Connection connection = JDBCConnection.connect();
	         String source2="";
	         StringBuffer source2buffer= null; //String for the comparison output
	         
	         ResultSet rs = JDBCConnection.executeQuery("SELECT CONTENT FROM sitemonitor.SITEMONITORDETAIL WHERE URL='"+url+"' ORDER BY DATETIME DESC ");
	         if(rs.next()){
	        	 source2=rs.getString(1);
	        	 fileout = new FileOutputStream(new File(tempHtml1FileName));
		         fileout.write(source2.getBytes());
		         fileout.close();
		 
		     
		         BufferedReader br1 = new BufferedReader(new InputStreamReader(new FileInputStream(new File(tempHtmlFileName))));
		         BufferedReader br2 = new BufferedReader(new InputStreamReader(new FileInputStream(new File(tempHtml1FileName))));
		         String strLine1=null;
		         String strLine2=null;
		         int line =1;
		         boolean isheaderwritten=false;
		         while((strLine1 = br1.readLine()) != null && (strLine2 = br2.readLine()) != null){  
		             if(!strLine1.trim().equals(strLine2.trim())){
		            	 if(!isheaderwritten){
		            		 source2buffer= new StringBuffer("line Number,Last Recent Content,Current Content\n");
		            		 isheaderwritten=true;
		            	 }
		            	 source2buffer.append(line+","+strLine1+","+strLine2+"\n");   
		             }  
		             line++;
		         } 
		     
	         }        
	         
	       
	        	 
	         Calendar cal = Calendar.getInstance();
	         PreparedStatement stmnt = connection.prepareStatement("INSERT INTO sitemonitor.SITEMONITORDETAIL(Url,Content,DateTime) VALUES( ?,?,?)");
	         stmnt.setString(1, url);
	         stmnt.setString(2, source.trim()); //put the xml and not html
	         stmnt.setTimestamp(3, new java.sql.Timestamp(cal.getTimeInMillis()));
	         stmnt.execute();
	         stmnt.close();
	         
	         if(source2buffer != null){	        	 
                 stmnt = connection.prepareStatement("INSERT INTO sitemonitor.SITEMONITORDIFF(Url,DiffContent,DateTime) VALUES( ?,?,?)");
    	         stmnt.setString(1, url);
    	         stmnt.setString(2, source2buffer.toString().trim());
    	         stmnt.setTimestamp(3, new java.sql.Timestamp(cal.getTimeInMillis()));
    	         stmnt.execute();
    	         stmnt.close();	 
	         }
                              

		 }catch(Exception e){
			 e.printStackTrace();
		 }
        
	 }
	
	
//	 public static void getBodyHTML(String url,WebDriver driver){
//		 try{
//			 //String htmlString = "";
//			 String filename="D:\\temp.jpg";
//			 String fileoldname="D:\\tempold.jpg";
//			 driver.get(url);    
//	        
//			 
//		    Thread.sleep(3000);
//			File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//			// Now you can do whatever you need to do with it, for example copy somewhere
//			FileUtils.copyFile(scrFile, new File(filename));
//			saveJPG(ImageIO.read(new File(filename)),filename);
//
//	         
//	         Connection connection = JDBCConnection.connect();
//	         StringBuffer source2buffer= null; //String for the comparison output
//	         
//	         ResultSet rs = JDBCConnection.executeQuery("SELECT CONTENT FROM sitemonitor.SITEMONITORDETAIL WHERE URL='"+url+"' ORDER BY DATETIME DESC ");
//	         if(rs.next()){
//	        	 byte[] result=rs.getBytes(1);
//	        	 FileOutputStream fileout = new FileOutputStream(new File(fileoldname));
//		         fileout.write(result);
//		         fileout.close();
//		 
//		     
//	         }        
//	         
//	       
//	        	 
//	         Calendar cal = Calendar.getInstance();
//	         PreparedStatement stmnt = connection.prepareStatement("INSERT INTO sitemonitor.SITEMONITORDETAIL(Url,Content,DateTime) VALUES( ?,?,?)");
//	         stmnt.setString(1, url);
//	         stmnt.setString(2, source.trim()); //put the xml and not html
//	         stmnt.setTimestamp(3, new java.sql.Timestamp(cal.getTimeInMillis()));
//	         stmnt.execute();
//	         stmnt.close();
//	         
//	         if(source2buffer != null){	        	 
//                 stmnt = connection.prepareStatement("INSERT INTO sitemonitor.SITEMONITORDIFF(Url,DiffContent,DateTime) VALUES( ?,?,?)");
//    	         stmnt.setString(1, url);
//    	         stmnt.setString(2, source2buffer.toString().trim());
//    	         stmnt.setTimestamp(3, new java.sql.Timestamp(cal.getTimeInMillis()));
//    	         stmnt.execute();
//    	         stmnt.close();	 
//	         }
//                              
//
//		 }catch(Exception e){
//			 e.printStackTrace();
//		 }
//        
//	 }
//	 
//	 protected static void saveJPG(Image img, String filename) {
//			BufferedImage bi = imageToBufferedImage(img);
//			FileOutputStream out = null;
//			try { 
//				out = new FileOutputStream(filename);
//			} catch (java.io.FileNotFoundException io) { 
//				System.out.println("File Not Found"); 
//			}
//			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
//			param.setQuality(0.8f,false);
//			encoder.setJPEGEncodeParam(param);
//			try { 
//				encoder.encode(bi); 
//				out.close(); 
//			} catch (java.io.IOException io) {
//				System.out.println("IOException"); 
//			}
//		}
//		
//		protected static BufferedImage imageToBufferedImage(Image img) {
//			BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
//			Graphics2D g2 = bi.createGraphics();
//			g2.drawImage(img, null, null);
//			return bi;
//		}
	
	
}